package com.demarc.pesquisas.web.converter;

import java.math.BigDecimal;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.faces.convert.NumberConverter;

import com.demarc.pesquisas.infraestrutura.mensagem.MensagemJsfUtils;
import com.demarc.pesquisas.infraestrutura.web.jsf.JsfUtil;
import com.demarc.pesquisas.negocio.util.NumberUtils;

@FacesConverter(value = "BigDecimalConverter", forClass = BigDecimal.class)
public class BigDecimalConverter extends NumberConverter {

	private static final String BIG_DECIMAL_MESSAGE_ID = "com.demarc.pesquisas.web.converter.BigDecimalConverter.BIGDECIMAL";

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object input) {
		String value = null;

		if (input instanceof BigDecimal) {
			value = NumberUtils.convertToString((BigDecimal) input);
		}
		return value;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String input) {

		try {
			return NumberUtils.converterDeStringParaBigDecimal(input);
		} catch (Exception e) {
			FacesMessage facesMessage = MensagemJsfUtils.criarFacesMessage(
					FacesMessage.SEVERITY_ERROR, BIG_DECIMAL_MESSAGE_ID,
					JsfUtil.getLabel(context, component));
			throw new ConverterException(facesMessage, e);
		}
	}
}